import fs from 'fs'
import { parse } from 'path'
import { success } from './output'

// 读文件，可选择是否解析为 JSON，对一些错误作了处理
const reader = (path: string, parse: boolean = true): Promise<any> => {
  return new Promise((resolve, reject) => {
    fs.stat(path, async (_, stat) => {
      if (stat?.isFile()) {
        fs.readFile(path, 'utf-8', (err, data) => {
          if (parse) {
            try {
              const res: object | string = data && JSON.parse(data) || ''
              err ? reject(err) : res ? resolve([false, res]) : reject('文件内容为空')
            } catch (e) {
              reject(new Error('文件解析错误'))
            }
          } else {
            resolve([false, data])
          }
        })
      } else {
        resolve([true, null])
      }
    })
  })
}

// 写文件
const writer = (path: string, data: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, err => {
      err ? reject('文件写入错误') : resolve()
    })
  })
}

// 删除文件
const removeFiles = async (path: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    fs.unlink(path, err => err ? reject(err) : resolve())
  })
}

// 若文件夹不存在则创建
const checkDir = (path: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    fs.access(path, err => {
      err ? fs.mkdir(path, e => (e ? reject(e) : resolve())) : resolve()
    })
  })
}

// 获取文件夹下所有文件
const getFiles = (path: string ): Promise<Array<string>> => {
  return new Promise((resolve, reject) => {
    fs.readdir(path, (err, files) => {
      err ? reject(err) : resolve(files)
    })
  })
}

// 获取指定路径下的指定后缀文件的文件名
const getFileNamesBySuffix = async (path: string, suffix: string) => {
  const files = await getFiles(path)
  return files
    .filter(file => file.endsWith(suffix))
    .map(file => parse(file).name)
}

export { reader, writer, removeFiles, checkDir, getFiles, getFileNamesBySuffix }
